package com.hailiao.beidou.message.ui.page.contacts

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.d10ng.common.calculate.isOnlyNumber
import com.d10ng.common.transform.toPinYin
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.compose.ui.dialog.builder.ConfirmDialogBuilder
import com.hailiao.beidou.message.data.contact.ContactRepository
import com.hailiao.beidou.message.data.db.entity.ContactEntity
import com.hailiao.beidou.message.ui.page.destinations.ChatScreenDestination
import com.hailiao.beidou.message.ui.page.destinations.HomeScreenDestination
import com.hailiao.beidou.message.ui.page.navArgs
import com.hailiao.beidou.message.utils.NavControllerUtils
import com.hailiao.beidou.message.utils.back
import com.hailiao.beidou.message.utils.go
import com.ramcosta.composedestinations.navigation.popUpTo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * 联系人详情
 * @Author d10ng
 * @Date 2024/3/2 16:41
 */
data class ContactDetailScreenNavArgs(
    val number: String? = null
)

class ContactDetailScreenViewModel(
    savedStateHandle: SavedStateHandle
): ViewModel() {
    private val navArgs = savedStateHandle.navArgs<ContactDetailScreenNavArgs>()

    // 是否为编辑模式
    val isEditFlow = MutableStateFlow(navArgs.number != null)
    // 联系人信息
    val infoFlow = MutableStateFlow(ContactEntity())

    init {
        viewModelScope.launch {
            if (isEditFlow.value) {
                val info = ContactRepository.get(navArgs.number!!)
                if (info != null) infoFlow.value = info
                else isEditFlow.value = false
            }
        }
    }

    /**
     * 更新联系人信息
     * @param value ContactEntity
     */
    fun updateInfo(value: ContactEntity) {
        infoFlow.value = value
    }

    /**
     * 点击保存
     */
    fun onClickSave() {
        viewModelScope.launch {
            if (save()) {
                UiViewModelManager.showSuccessToast("操作成功")
                back()
            }
        }
    }

    /**
     * 点击发送信息
     */
    fun onClickSend() {
        viewModelScope.launch {
            if (save()) {
                // 跳转信息发送页并且回到对话框列表页
                go(ChatScreenDestination(infoFlow.value.number).route) {
                    launchSingleTop = true
                    popUpTo(HomeScreenDestination)
                }
            }
        }
    }

    /**
     * 点击删除
     */
    fun onClickDelete() {
        UiViewModelManager.showDialog(ConfirmDialogBuilder(
            content = "删除后历史信息无法恢复，确定要删除吗？",
            onConfirmClick = {
                viewModelScope.launch {
                    UiViewModelManager.showLoading()
                    ContactRepository.delete(infoFlow.value)
                    UiViewModelManager.hideLoading()
                    NavControllerUtils.getTop()?.apply {
                        if (previousBackStackEntry?.destination?.route == ChatScreenDestination.route) {
                            popBackStack(ChatScreenDestination.route, true)
                        } else popBackStack()
                    }
                }
                true
            }
        ))
    }

    /**
     * 保存信息
     * @return Boolean
     */
    private suspend fun save(): Boolean {
        if (check().not()) return false
        // 更新拼音
        infoFlow.value.pinyin = infoFlow.value.name.toPinYin()
        if (isEditFlow.value) ContactRepository.update(infoFlow.value)
        else ContactRepository.insert(infoFlow.value)
        return true
    }

    /**
     * 检查输入内容
     * @return Boolean
     */
    private suspend fun check(): Boolean {
        val info = infoFlow.value
        if (info.number.isEmpty()) {
            UiViewModelManager.showErrorNotify("卡号不能为空！")
            return false
        }
        if (info.number.isOnlyNumber().not()) {
            UiViewModelManager.showErrorNotify("卡号只能为数字！")
            return false
        }
        if (info.number.length !in listOf(7, 8, 11)) {
            UiViewModelManager.showErrorNotify("卡号长度不在有效范围！")
            return false
        }
        if (info.name.isEmpty()) {
            UiViewModelManager.showErrorNotify("姓名不能为空！")
            return false
        }
        if (!isEditFlow.value && ContactRepository.get(infoFlow.value.number) != null) {
            UiViewModelManager.showErrorNotify("该卡号已存在！")
            return false
        }
        return true
    }
}